package com.pioneer.app.sms.mobile;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

import org.hibernate.Transaction;

import com.pioneer.app.dev.osuser.user.Userlist;
import com.pioneer.app.dev.osuser.user.UserlistDAO;
import com.pioneer.app.sms.log.SmsSendLog;
import com.pioneer.app.sms.log.SmsSendLogDAO;

import config.SMSConfig;

public class SendService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(SendService.class);

	public List mobiles=new ArrayList();
	public String title;
	public String content;
	public String sendtime;
	public String priority="1";
	public Map fullInfor=new HashMap();
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getSendtime() {
		return sendtime;
	}
	public void setSendtime(String sendtime) {
		this.sendtime = sendtime;
	}
	
	public void setUsers(String userId){
		if(null!=userId && !"".equals(userId)){
			if(userId.endsWith(";")){
				userId=userId.substring(0, userId.length()-1);
			}
			UserlistDAO dao=new UserlistDAO();
			List users=dao.findByCondition("id in ("+userId+")");
			if(null!=users){
				Iterator it=users.iterator();
				Userlist user=null;
				while(it.hasNext()){
					user=(Userlist)it.next();
					this.mobiles.add(user.getTelphone());
				}
			}
		}
		
	}
	private static Vector stringToVector(String sourceStr, String separator) {
		Vector result = new Vector();
		if (sourceStr.indexOf(separator) == -1) {
			result.addElement(sourceStr);
			return result;
		}
		String tmpStr = "";
		while (sourceStr.indexOf(separator) != -1) {
			tmpStr = strLeft(sourceStr, separator);
			result.addElement(tmpStr);
			sourceStr = strRight(sourceStr, separator);
		}
		if (!(sourceStr.equals(""))) {
			result.addElement(sourceStr);
		}
		return result;
	}
	private static String strLeft(String sourceStr, String separator) {
		if (sourceStr.length() == 0 || separator.length() == 0) {
			return "";
		} else {
			if (sourceStr.indexOf(separator) == -1) {
				return sourceStr;
			} else {
				return sourceStr.substring(0, sourceStr.indexOf(separator));
			}

		}
	}

	private static String strRight(String sourceStr, String separator) {
		if (sourceStr.length() == 0 || separator.length() == 0) {
			return "";
		} else {
			if (sourceStr.indexOf(separator) == -1) {
				return sourceStr;
			} else {
				return sourceStr.substring(sourceStr.indexOf(separator)
						+ separator.length(), sourceStr.length());
			}
		}
	}
	public void setMobile(String mobilesStr){
		if(null!=mobilesStr && !"".equals(mobilesStr.trim())){
			String[] mobils=null;
			Vector vector=null;
			if(-1!=mobilesStr.indexOf(";")){
				mobils=mobilesStr.split(";");
			}else if(-1!=mobilesStr.indexOf("||")){
				vector=stringToVector(mobilesStr,"||");
//				mobils=mobilesStr.split("||");
			}else{
				if(null!=mobilesStr && !"".equalsIgnoreCase(mobilesStr.trim()))
					this.mobiles.add(mobilesStr);
			}
//			if(null==mobils)return ;
			if(null==vector)return ;
//			int l=mobils.length;
			int l=vector.size();
			for(int i=0;i<l;i++){
				String tmp=(String)vector.get(i);
				if(null!=tmp && !"".equalsIgnoreCase(tmp.trim()))
					this.mobiles.add(tmp);
			}
			
		}
	}
	
	public void setEXCELSMSFile(File file){
		if(null!=file && file.exists()){
			
			try {
				FileInputStream is=new FileInputStream(file);
				WorkbookSettings workbookSettings = new WorkbookSettings();
        workbookSettings.setEncoding("UTF-8");
        Workbook rwb = Workbook.getWorkbook(is, workbookSettings);
        Sheet st = rwb.getSheet(0);
        int length = st.getRow(1).length;
  			int rownum = st.getRows();
  			
  			for (int i = 2; i < rownum; i++) {
  				String contentStr=this.content+"";
  				Cell[] cells = st.getRow(i);
  				if (length < cells.length)
  					length = cells.length;
  				System.out.println("name="+cells[0].getContents());
  				for(int j=0;j<length;j++){
  					String oldStr="{"+j+"}";
  					contentStr=this.replace(contentStr, oldStr, cells[j].getContents());
  				}
  				String mobile=cells[1].getContents();
  				if(null!=mobile && !"".equals(mobile.trim()))
  					this.fullInfor.put(mobile, contentStr);
//  				contentStr=this.replace(contentStr, "{1}", cells[1].getContents());
  			}
			}catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		
	}
	
	public void setMobileFile(File file){
		if(null!=file && file.exists()){
			
			try {
//				FileInputStream fin=new FileInputStream(file);
				FileReader fread=new FileReader(file);
				BufferedReader reader = new BufferedReader(fread);
				String line=null;
				
				line=reader.readLine();
				int t=0;
				while(true){
					if(null!=line && !"".equals(line.trim())){
						this.mobiles.add(line);
					}else{
						t++;
						if(t>20)break;
					}
					line=reader.readLine();
				}
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		
	}
	
	public void setSMS(){
		

		Iterator it=this.mobiles.iterator();
		String moblie;
		//System.out.println("标题:"+title+"    内容："+content);
		SmsSendLog smsobj =null;
		SmsSendLogDAO smsDao=new SmsSendLogDAO();
		Transaction tx=smsDao.getSession().beginTransaction();
		while(it.hasNext()){
			moblie=(String)it.next();
			smsobj=new SmsSendLog();
			smsobj.setTitle(title);
			smsobj.setContent(content);
			smsobj.setToMobile(moblie);
			smsobj.setSendTime(new Date());
			smsobj.setStatus("提交");
			smsDao.add(smsobj);
			try{
				
				sendSMS(content,moblie,priority,String.valueOf(smsobj.getSendLogId()),SMSConfig.getInst().getSysCode(),SMSConfig.getInst().getExctenNumber());
			}catch(Exception e){
				logger.error("短信发送失败 标题："+title+" \r\n内容： "+content+"\r\n 号码："+moblie);
				logger.error("setSMS()", e);

				//tx.commit();
				
				smsobj.setStatus("失败");
				smsDao.update(smsobj);
				throw new RuntimeException();
//				continue;
			}
		}
		//tx.commit();
//		exceln内容的发送
		Iterator smsit=this.fullInfor.keySet().iterator();
		while(smsit.hasNext()){
			moblie=(String)smsit.next();
			String contentStr=(String)this.fullInfor.get(moblie);
			smsobj=new SmsSendLog();
			smsobj.setTitle(title);
			smsobj.setContent(contentStr);
			smsobj.setToMobile(moblie);
			smsobj.setSendTime(new Date());
			smsobj.setStatus("提交");
			smsDao.add(smsobj);
			try{
				
				sendSMS(contentStr,moblie,priority,String.valueOf(smsobj.getSendLogId()),SMSConfig.getInst().getSysCode(),SMSConfig.getInst().getExctenNumber());
			}catch(Exception e){
				logger.error("setSMS()", e);
				
				smsobj.setStatus("失败");
				smsDao.update(smsobj);
				continue;
			}
		}
		tx.commit();
		if (logger.isDebugEnabled()) {
			logger.debug("setSMS() - end");
		}
	}
	
	public static void sendSMS(String content, String mobilePhones, String priority,String messageFlag, String moduleName, String exNumber)throws Exception
	{
		String strURL = SMSConfig.getInst().getSMSServiceURL();
		//System.out.println(""+strURL);
		String response = "";
		boolean success = false;
        try {
    		strURL += "?MobilePhones=" + mobilePhones
			+ "&Content=" + java.net.URLEncoder.encode(content,"GBK")
			+ "&Priority=" + priority 
			+ "&ExNumber=" + exNumber 
			+ "&MessageFlag=" + messageFlag 
			+ "&ModuleName=" + moduleName;
            URL objURL = new URL(strURL);
            URLConnection objConn = objURL.openConnection();
            objConn.setDoInput(true);
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    objConn.getInputStream()));
            String line = br.readLine();
            while (line != null) {
                response += line;
                line = br.readLine();
            }
            br.close();
            success = true;
        } catch (Exception e) {
        	throw e;
        }

	}
	
	private String replace(String source, String oldString,String newString){
		StringBuffer output = new StringBuffer();
		int lengthOfSource = source.length();
		int lengthOfOld = oldString.length();
		int posStart = 0;
		int pos; //
		while ( (pos = source.indexOf(oldString, posStart)) >= 0){
		output.append(source.substring(posStart, pos));
		output.append(newString);
		posStart = pos + lengthOfOld;
		}
		if (posStart < lengthOfSource){
		output.append(source.substring(posStart));
		}
		return output.toString();
}
}
